package cn.awit.net.jwt.utl.jdbc;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

/**
 * <B>说 明</B>:连接池类
 * 
 * @author 作 者 名：张鸿杰<br/>
 *         E-mail ：zhanghongjie@qq.com
 * 
 * @version 版 本 号：V1.0.20130718<br/>
 *          创建时间：2014年08月10日 上午16:14:10
 */
public class ConnectionPool {

	public String mConfigFilePath;
	public DataSource mDataSource = null;
	public static ConnectionPool pool = null;
	public static QueryRunner queryRunner = null;
	
	private static final String DRIVER_NAME="com.microsoft.sqlserver.jdbc.SQLServerDriver";
	private static final String URL="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=guiyang_weather_os";
	private static final String USER="sa";
	private static final String PASSWORD="Awit1024";

	public static QueryRunner getQueryRunner() {
		return queryRunner;
	}

	public ConnectionPool() {
		
	}

	/**
	 * 单例
	 * 
	 */
	public static synchronized ConnectionPool getInstance()
			throws Exception {
		if (pool == null) {
			pool = new ConnectionPool();
			// 初始化连接池
			if (pool.mDataSource == null) {
				pool.mDataSource = pool.setupDataSource();

			}
			queryRunner = new QueryRunner(pool.mDataSource);
		}

		return pool;
	}

	public ConnectionPool(String contextPath) throws Exception {
		this.mDataSource = setupDataSource();

	}

	private DataSource setupDataSource() throws Exception {

		Properties prop = new Properties();

		FileInputStream file = new FileInputStream("db.properties");

		try {
			prop.load(file);
//			DriverManager.getConnection(prop.getProperty("url"), prop.getProperty("user"), prop.getProperty("password"));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			file.close();
		}
		return DruidDataSourceFactory.createDataSource(prop);
	}

	/**
	 * 获取连接
	 * @return
	 * @throws Exception
	 */
	public Connection getConnection() throws Exception {
		return mDataSource.getConnection();
	}
	
	/**
	 * 关闭连接
	 * @param con
	 * @throws SQLException
	 */
	public void releaeConnection(Connection con) throws SQLException {
		if (con != null) {
			con.close();

		}
	}

}
